//
//  ViewController.m
//  SimulationTechnologyHeadlines
//
//  Created by 移云 on 2019/10/17.
//  Copyright © 2019 admin. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "XDRefreshView.h"
#import "NewsCellFootView.h"
#import "NewsCell.h"
#import "News.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,NewsCellFootViewDeleagte>
@property(nonatomic,strong)NSMutableArray *newsArr;
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong) XDRefreshView *refreahView;
@property (nonatomic, strong) UIRefreshControl* refreshControl;
@property(nonatomic,weak)UIImageView *tableHeaderImageView;
@property(nonatomic,strong)NewsCellFootView *footView;
@end

@implementation ViewController

#pragma mark - 懒加载

- (NSMutableArray *)newsArr
{
    if (_newsArr == nil)
    {
        _newsArr = [NSMutableArray array];
    }
    return _newsArr;
}
/**
 * 创建下拉刷新控件
 */
-(XDRefreshView *)refreahView{

    if (_refreahView==nil) {
        _refreahView = [[XDRefreshView alloc] initWithFrame:CGRectMake(0,-60, [UIScreen mainScreen].bounds.size.width, 60)];
    }
    return _refreahView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    [self getNewsDataWith:0];
    
   
    
    //添加刷新控件到tableView上
    [self.tableView addSubview:self.refreahView];
    //1定义block  ： refreahView.refreshBlock
    //2传递block（赋值）：refreahView.refreshBlock = ^()
    self.refreahView.refreshBlock = ^(){
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //加载数据
            [self.newsArr removeAllObjects];
            [self.tableView reloadData];
            [self getNewsDataWith:0];
            [self.refreahView endRefreshing];
        });
        
        
    };

    NewsCellFootView *footView = [[NewsCellFootView alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 60)];
    self.footView = footView;
    self.tableView.tableFooterView = footView;
    footView.delegate = self;
    
}


- (void)setupUI
{
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 20)];
    [self.view addSubview:topView];
    
    UILabel *topLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width/2 - 20, 5, 40, 20)];
    topLabel.text = @"推荐";
    [topView addSubview:topLabel];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 59, self.view.bounds.size.width, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineView];
    
    UIView *tableHeaderView = [[UIView alloc]init];
    [tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view.bounds.size.width);
        make.height.mas_equalTo(150);
    }];
    
    UIImageView *tableHeaderImageView = [[UIImageView alloc]init];
    self.tableHeaderImageView = tableHeaderImageView;
    tableHeaderImageView.contentMode = UIViewContentModeScaleAspectFill;
    tableHeaderImageView.layer.cornerRadius = 6;
    tableHeaderImageView.layer.masksToBounds = YES;
    [tableHeaderView addSubview:tableHeaderImageView];
    tableHeaderImageView.backgroundColor = [UIColor lightGrayColor];
    [tableHeaderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(tableHeaderView).offset(10);
        make.right.bottom.equalTo(tableHeaderView).offset(-10);
    }];
    
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, self.view.bounds.size.width, self.view.bounds.size.height - 60)];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.tableHeaderView = tableHeaderView;


    UIView *noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 60, self.view.bounds.size.width, self.view.bounds.size.height - 60)];
    [self.view addSubview:noDataView];
    
    UIImageView *noDataImageView = [[UIImageView alloc] init];
    noDataImageView.image = [UIImage imageNamed:@"Mask"];
    [noDataView addSubview:noDataImageView];
    [noDataImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(390);
        make.height.mas_equalTo(100);
        make.width.mas_equalTo(self.view.bounds.size.width);
    }];
    
    UILabel *noDataLabel = [[UILabel alloc]init];
    noDataLabel.text = @"NO DATA";
    noDataLabel.textColor = [UIColor lightGrayColor];
    [noDataView addSubview:noDataLabel];
    [noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(noDataImageView.mas_bottom).offset(5);
        make.centerX.equalTo(noDataView.mas_centerX);
    }];
    
    self.tableView.backgroundView = noDataView;
   
   
}

#pragma mark - tableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NewsCell *cell = [NewsCell newsCellWithTableView:tableView];
    
    cell.newsModel = self.newsArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中效果
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    News *newsModel = self.newsArr[indexPath.row];
    
    WKWebView *webView = [[WKWebView alloc]init]; //初始化UIWebView
    webView.frame = [UIScreen mainScreen].bounds; //设置位置
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:newsModel.url]]];
    
    UIPageViewController *articleVC= [[UIPageViewController alloc] init];
    UINavigationController *nvCtl = [[UINavigationController alloc] initWithRootViewController:articleVC];

    articleVC.navigationItem.title = newsModel.nickname;
    
    [articleVC.view addSubview:webView]; //添加网页
    [self presentViewController:nvCtl animated:YES completion:nil];
    
}

//悬浮table
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//
//    UIView *topView = [[UIView alloc]init];
//
//    topView.backgroundColor = [UIColor linkColor];
//    return topView;
//}

#pragma mark - 加载更多数据
- (void)newsCellFootViewUpdata:(NewsCellFootView *)newsCellFootView
{
    static int loadMorePageNum = 1;
    [self getNewsDataWith:loadMorePageNum];
    loadMorePageNum += 1;
    
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //把UITableView中的最后一行滚动到
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.newsArr.count - 8 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        
        self.footView.loadMoreButton.hidden = false;
        self.footView.loadingLabel.hidden = true;
        [self.footView.actIndicatorView stopAnimating];
        
    });
   
}



#pragma mark - 发送异步请求获取数据
- (void)getNewsDataWith:(int)page
{
    
    //代码重构
    {
//    NSString *urlStr = [NSString stringWithFormat:@"http://kjtt.wokeji.com/index/push-arcs?access-token=KzYDcKOAPkM4b2snv2EHdstYrkTLTw6u&page=%d&sort=1",page];
//
//    NSLog(@"%@",urlStr);
//    //该地址尽管是XML数据，但是请求返回的是个字典
//    NSURL *url = [NSURL URLWithString:urlStr];
//
//
//
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
//    [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//
//        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",str);
//
//        // 将字符串转换成字典
//        NSData * getJsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:NULL];
//
//        //字典转模型
//        NSArray *arrayDic = getDict[@"data"];
//
//        for (NSDictionary *dic in arrayDic)
//        {
//            News *newsModel = [News newsWithDic:dic];
//            [self.newsArr addObject:newsModel];
//        }
//
//        [self.tableView reloadData];
//    }];
    }
    
    [News requestNewsDataWithPage:page AndSuccess:^(NSArray * _Nonnull arrayDic) {
        for (NSDictionary *dic in arrayDic)
        {
            News *newsModel = [News newsWithDic:dic];
            [self.newsArr addObject:newsModel];
        }
        [self.tableView reloadData];
        
        News *newsPic = self.newsArr[0];
        NSURL *picURL = [NSURL URLWithString:newsPic.picurl];
        NSData *picData = [NSData  dataWithContentsOfURL:picURL];
        UIImage *image = [UIImage imageWithData:picData];
        self.tableHeaderImageView.image = image;
       
    } AndError:^(NSString * _Nonnull errorStr) {
        [self tipWithMessage:errorStr];
    }];
    
}


#pragma mark - 最简单的下来刷新
- (void)simplePullDownRefresh
{
    _refreshControl = [[UIRefreshControl alloc] init];
       [_refreshControl addTarget:self
                         action:@selector(refreshView:)
               forControlEvents:UIControlEventValueChanged];
       [_refreshControl setAttributedTitle:[[NSAttributedString alloc] initWithString:@"松手更新数据"]];
       [self.tableView addSubview:_refreshControl];
}

-(void) refreshView:(UIRefreshControl *)refresh
{
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"更新数据中..."];
     
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM d, h:mm a"];
    NSString *lastUpdated = [NSString stringWithFormat:@"上次更新日期 %@",
                             [formatter stringFromDate:[NSDate date]]];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //加载数据
        [self.newsArr removeAllObjects];
        [self.tableView reloadData];
        [self getNewsDataWith:0];
        [refresh endRefreshing];
    });
}

//提示弹窗
- (void)tipWithMessage:(NSString *)message
{

      UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(UIScreen.mainScreen.bounds.size.width/2 - 60, UIScreen.mainScreen.bounds.size.height/2, 120, 30)];
      // 设置提示内容
      [tipLabel setText:message];
      tipLabel.backgroundColor = [UIColor blackColor];
      tipLabel.layer.cornerRadius = 5;
      tipLabel.layer.masksToBounds = YES;
      tipLabel.textAlignment = NSTextAlignmentCenter;
      tipLabel.textColor = [UIColor whiteColor];
      [self.view addSubview:tipLabel];
      // 设置时间和动画效果
      [UIView animateWithDuration:2.0 animations:^{
      tipLabel.alpha = 0.0;
      } completion:^(BOOL finished) {
      // 动画完毕从父视图移除
      [tipLabel removeFromSuperview];
      }];
    
}


@end
